<template>
  <el-drawer v-model="isShowDrawer" custom-class="drawer" :before-close="onBeforeClose" size="30%" :destroy-on-close="true" @closed="onClosed">
    <template #header>
      <h4 class="drawer-header">忘记密码</h4>
    </template>
    <template #default>
      <div class="drawer-content">
        <!-- 第一步: 选身份 -->
        <el-form :model="roleData" label-width="80px">
          <el-form-item label="您的身份" prop="role">
            <el-radio-group v-model="roleData.role" @change="onRoleChange">
              <el-radio label="teacher" border>教 师</el-radio>
              <el-radio label="student" border>学 生</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <!-- 第二步: 根据身份填不同的信息 -->
        <!-- 教师 -->
        <el-form v-if="roleData.role === 'teacher'" ref="tchFormRef" :disabled="isLastStep" :model="tchFormData" :rules="rules" label-width="80px">
          <el-form-item label="工号" prop="workId">
            <el-input v-model="tchFormData.workId" placeholder="您的工号(不带TCH)" clearable />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="tchFormData.name" placeholder="您的姓名" clearable />
          </el-form-item>
          <el-form-item label="身份证号" prop="identityId">
            <el-input v-model="tchFormData.identityId" placeholder="您的身份证号" clearable />
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="tchFormData.phone" placeholder="您的联系电话" clearable />
          </el-form-item>
          <el-form-item label="期数" prop="stage">
            <el-input v-model="tchFormData.stage" placeholder="您所教过的任意一个期数" clearable />
          </el-form-item>
          <el-form-item label="部门" prop="department">
            <el-input v-model="tchFormData.department" placeholder="与上面期数对应的部门号" clearable />
          </el-form-item>
        </el-form>
        <!-- 学生 -->
        <el-form v-if="roleData.role === 'student'" ref="stuFormRef" :disabled="isLastStep" :model="stuFormData" :rules="rules" label-width="80px">
          <el-form-item label="学号" prop="studentId">
            <el-input v-model="stuFormData.studentId" placeholder="您的学号(不带STU)" clearable />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="stuFormData.name" placeholder="您的姓名" clearable />
          </el-form-item>
          <el-form-item label="身份证号" prop="identityId">
            <el-input v-model="stuFormData.identityId" placeholder="您的身份证号" clearable />
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="stuFormData.phone" placeholder="您的联系电话" clearable />
          </el-form-item>
          <el-form-item label="期数" prop="stage">
            <el-input v-model="stuFormData.stage" placeholder="您的期数" clearable />
          </el-form-item>
          <el-form-item label="部门" prop="department">
            <el-input v-model="stuFormData.department" placeholder="与上面期数对应的部门号" clearable />
          </el-form-item>
        </el-form>
        <!-- 第三步: 修改密码 -->
        <el-form v-show="isLastStep" ref="submitFormRef" :model="modifyPwd" :rules="rules" label-width="80px">
          <el-form-item label="密码:" prop="one">
            <el-input v-model="modifyPwd.one" clearable show-password> </el-input>
          </el-form-item>
          <el-form-item label="确认密码:" prop="two">
            <el-input v-model="modifyPwd.two" clearable show-password />
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="isShowDrawer = false">取 消</el-button>
        <el-button v-show="isLastStep" @click="isLastStep = false">上一步</el-button>
        <el-button type="primary" @click="confirmClick">{{ confirmBtnText }}</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { computed, ref, watch } from 'vue';
import { useAPI } from '../../request/api';
import { useUserStore } from '../../store/user';
import { useRuleUtils } from '../../utils/validate';
import { APIData, IForgetTchPwd, IForgetsStuPwd, IModifyPwd } from '../../type/index';

interface IStuFormData {
  name: string;
  studentId: string;
  identityId: string;
  phone: string;
  stage: number;
  department: number;
}
interface ITchFormData {
  name: string;
  workId: string;
  identityId: string;
  phone: string;
  stage: number;
  department: number;
}
interface IPassword {
  one: string;
  two: string;
}
interface IProps {
  isShow: boolean;
}

watch(
  () => props.isShow,
  neValue => {
    isShowDrawer.value = neValue;
  }
);

const confirmBtnText = computed(() => {
  if (isLastStep.value) return '确认修改';
  else return '下一步';
});

const api = useAPI();
const ruleUtils = useRuleUtils();
const props = defineProps<IProps>();

const tchFormRef = ref();
const stuFormRef = ref();
const submitFormRef = ref();
const tchFormData = ref({} as ITchFormData);
const stuFormData = ref({} as IStuFormData);
let validateTchRes = {} as IForgetTchPwd;
let validateStuRes = {} as IForgetsStuPwd;
const modifyPwd = ref({} as IPassword);
const roleData = ref({ role: 'teacher' } as { role: string });
const isShowDrawer = ref<boolean>(false);
const isLastStep = ref<boolean>(false);

const onRoleChange = () => {
  isLastStep.value = false;
  // tchFormData.value = {} as ITchFormData;
  // stuFormData.value = {} as IStuFormData;
  modifyPwd.value = {} as IPassword;
};

const confirmClick = () => {
  let formEl: FormInstance | undefined;
  if (roleData.value.role === 'teacher') formEl = tchFormRef.value;
  if (roleData.value.role === 'student') formEl = stuFormRef.value;
  if (!formEl) return;

  formEl.validate(async (valid: any) => {
    if (valid) {
      if (roleData.value.role === 'teacher') tchSubmit(); //如果正确，则已关闭抽屉
      if (roleData.value.role === 'student') stuSubmit(); //如果正确，则已关闭抽屉
    }
  });
};

const stuSubmit = () => {
  if (!isLastStep.value) validateStu();

  if (isLastStep.value) {
    const params: IModifyPwd = { id: validateStuRes.id, password: modifyPwd.value.one };
    submitModify(params, 'student');
  }
};

const tchSubmit = async () => {
  if (!isLastStep.value) validateTch();

  if (isLastStep.value) {
    const params: IModifyPwd = { id: validateTchRes.tchInfo.id, password: modifyPwd.value.one };
    submitModify(params, 'teacher');
  }
};

const validateStu = async () => {
  const formData = stuFormData.value;
  const params = { studentId: 'STU' + formData.studentId }; //手动添加 TCH前缀
  const result: APIData = await api.forgetPwd(params, 'student');
  if (result.code !== 200) ElMessage.error(result.message);
  else validateStuRes = result.data;

  let errorList: string[] = [];
  if (formData.name !== validateStuRes.name) errorList.push('姓名');
  if (formData.identityId !== validateStuRes.identityId) errorList.push('身份证');
  if (formData.phone !== validateStuRes.phone) errorList.push('手机号');

  let notCorrespond = '期数部门号错误或不对应';
  if (formData.stage == validateStuRes.stage && formData.department == validateStuRes.department) {
    notCorrespond = '';
  }

  let errorMessage = '';
  if (errorList.length !== 0 && notCorrespond === '') errorMessage = errorList.join('、') + '错误';
  if (errorList.length !== 0 && notCorrespond !== '') errorMessage = errorList.join('、') + '错误、' + notCorrespond;
  if (errorList.length === 0 && notCorrespond !== '') errorMessage = notCorrespond;

  if (errorMessage === '') isLastStep.value = true;
  else ElMessage.error(errorMessage);
};

const validateTch = async () => {
  const formData = tchFormData.value;
  const params = { workId: 'TCH' + formData.workId }; //手动添加 TCH前缀
  const result: APIData = await api.forgetPwd(params, 'teacher');
  if (result.code !== 200) ElMessage.error(result.message);
  else validateTchRes = result.data;

  let errorList: string[] = [];
  if (formData.name !== validateTchRes.tchInfo.name) errorList.push('姓名');
  if (formData.identityId !== validateTchRes.tchInfo.identityId) errorList.push('身份证');
  if (formData.phone !== validateTchRes.tchInfo.phone) errorList.push('手机号');

  let isAllRight = false;
  let notCorrespond = '';
  for (const item of validateTchRes.stageList) {
    if (formData.stage == item.stage && formData.department == item.department) {
      isAllRight = true;
      break;
    }
  }
  if (!isAllRight) notCorrespond = '期数部门号错误或不对应';

  let errorMessage = '';
  if (errorList.length !== 0 && isAllRight) errorMessage = errorList.join('、') + '错误';
  if (errorList.length !== 0 && !isAllRight) errorMessage = errorList.join('、') + '错误、' + notCorrespond;
  if (errorList.length === 0 && !isAllRight) errorMessage = notCorrespond;

  if (errorMessage === '') isLastStep.value = true;
  else ElMessage.error(errorMessage);
};

const submitModify = (params: IModifyPwd, role: string) => {
  let formEl = submitFormRef.value;
  if (!formEl) return;

  formEl.validate(async (valid: any) => {
    if (valid) {
      const modifyRes = await api.modifyPwd(params, role);
      if (modifyRes.data) {
        ElMessage.success('修改成功');
        isShowDrawer.value = false;
        validateTchRes = {} as IForgetTchPwd;
        validateStuRes = {} as IForgetsStuPwd;
      } else {
        ElMessage.error('服务器错误');
      }
    }
  });
};

const onBeforeClose = (done: () => void) => {
  ElMessageBox.confirm('关闭该页面后数据会清空,确定继续吗?', '提示', {
    confirmButtonText: '确 定',
    cancelButtonText: '取 消',
    type: 'warning',
  })
    .then(() => {
      done(); //关抽屉
    })
    .catch(() => {});
};

const emit = defineEmits(['onClosed']);
const onClosed = () => {
  let formEl: FormInstance | undefined;
  let submitFormEl = submitFormRef.value;

  if (roleData.value.role === 'teacher') {
    formEl = tchFormRef.value;
    tchFormData.value = {} as ITchFormData;
  }
  if (roleData.value.role === 'student') {
    formEl = stuFormRef.value;
    stuFormData.value = {} as IStuFormData;
  }
  if (!formEl) return;
  if (!submitFormEl) return;

  formEl.clearValidate();
  submitFormEl.clearValidate();

  roleData.value.role = 'teacher';

  emit('onClosed');
};

const confirmPwd = (rule: any, value: any, callback: any) => {
  if (!value || value === '') {
    callback(new Error('请输入密码'));
  } else if (!/^\S*(?=\S{6,})\S*$/.test(value)) {
    callback(new Error('密码长度不小于6位'));
  } else if (value !== modifyPwd.value.one) {
    callback(new Error('两次密码不一致'));
  } else {
    callback();
  }
};

const rules = {
  workId: [{ required: true, message: '必填项', trigger: 'blur' }],
  name: [{ required: true, message: '必填项', trigger: 'blur' }],
  studentId: [{ required: true, message: '必填项', trigger: 'blur' }],
  identityId: [{ validator: ruleUtils.identityId, trigger: 'blur' }],
  phone: [{ validator: ruleUtils.phone, trigger: 'blur' }],
  stage: [{ validator: ruleUtils.integer, trigger: 'blur' }],
  department: [{ validator: ruleUtils.integer, trigger: 'blur' }],
  one: [{ validator: ruleUtils.password, trigger: 'blur' }],
  two: [{ validator: confirmPwd, trigger: 'blur' }],
};
</script>

<style lang="scss" scoped>
.drawer-header {
  font-size: 18px;
  color: var(--font-color);
}
</style>
